/**
 * 
 */
package pt.mleiria.arduino;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author manuel
 *
 */
public class Dice {
	private InputStream _input;
	private OutputStream _output;
	
	private final Map<String, Integer> diceResults = new HashMap<String, Integer>();
	
	public Dice(final String portName, final int baudRate) throws Exception {
		final int timeout = 1000;
		final String appName = "OneDice";
		/*
		Enumeration<CommPortIdentifier> ports = CommPortIdentifier.getPortIdentifiers();
		while(ports.hasMoreElements()){
			System.out.println(ports.nextElement());
		}
		System.out.println(ports);
		*/
		CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
		
		
		SerialPort port = (SerialPort)portId.open(appName, timeout);
		_input = port.getInputStream();
		_output = port.getOutputStream();
		port.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
	}
	
	public void exec() throws Exception{
		byte[] buffer = new byte[255];
		Thread.sleep(2000);
		int i = 0;
		while(i < 5){
			_output.write("1".getBytes());//ou _output.write("1\n".getBytes());
			Thread.sleep(50);
			if(_input.available() > 0){
				_input.read(buffer);
				final String result = new String(buffer);
				System.out.print("READ:" + result);
				inferStats(result);
			}
			i++;
		}
		System.out.println(diceResults);
	}
	
	private void inferStats(final String result){
		Integer cnt = diceResults.get(result);
		if(cnt == null){
			cnt = 1;
		}else{
			cnt += 1;
		}
		diceResults.put(result, cnt);
	}

}
